package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @Title: cn.com.callback-apiBatchSignContract
 * @Description:ngsapitask-ph 合同批量发送
 * @Author: 胡策富
 * @Date 2023/8/4 14:30
 *
 */
public class apiBatchSignContract implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBatchSignContract.class);
    public static final String DATA_SOURCE = "dataSource";    //定义数据源常量
    private static final String CHARSET = "utf-8"; //设置字符集
    private static final Integer TIME_OUT = 100000; //设置请求超时时间
    private static final Integer ENABLE_SSL_FLAG = 0;

    static String LOCALURL;
    static String URL;
    static String CALLBACKURL;
    static String APPKEY;
    static String APPID;
    static Integer Incremental = 0;//合同编号递增

    // 设置的信号变量，最好使用volatile 关键字或者使用AtomicInteger原子类
    private volatile static int flag = 0;

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        JSONObject result = new JSONObject();
        String batchId = "";
        String recGuid = "";
        String method = request.getMethod();
        log.debug("获取请求方式：" + method);
        try {
            //获取回调类型
            String callbackType = request.getParameter("callbackType");
            log.debug("获取回调类型：" + callbackType);
            if (KHUtil.isNull(callbackType)) {
                result.put("code", 400);
                result.put("msg", "回掉类型必传");
                return result;
            }
            if (callbackType != "暂停") {
                batchId = Util.filterForObject(request.getParameter("batchId"));
                log.debug("获取传参批次号：" + batchId);
                if (KHUtil.isNull(batchId)) {
                    result.put("code", 400);
                    result.put("msg", "批次id必传");
                    return result;
                }
                //获取recGuid
                recGuid = Util.filterForObject(request.getParameter("recGuid"));
                log.debug("获取回调recGuid:" + recGuid);
            }

            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");//获取系统内部API调用服务域名地址
            URL = KHDBConfig.getAPIURL(eliteBean, "fddurl"); //获取法大大接口地址
            CALLBACKURL = KHDBConfig.getAPIURL(eliteBean, "callbackip");//外部调用接口ip
            APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");//获取法大大接口签名key
            APPID = KHDBConfig.getParam(eliteBean, "FDDID");//获取法大大appid
            switch (callbackType) {
                case "暂停":
                    flag = 1;
                    result.put("code", "200");
                    result.put("msg", "批次已暂停");
                    return result.toString();
                    break;
                case "批量发送":
                    flag = 0;
                    JSONObject pushContractResult = pushContract(eliteBean, batchId);
                    return pushContractResult.toString();
                    break;
                case "认证回调":
                    JSONObject resultJson = null;
                    //接收客户端调用参数
                    String callJson = "";
                    InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
                    BufferedReader iny = new BufferedReader(reader);
                    String line;
                    while ((line = iny.readLine()) != null) {
                        callJson += line;
                    }
                    log.info("[调用请求信息]:" + callJson);
                    JSONObject inJson = JSONObject.fromObject(callJson);
                    String bizContents = inJson.getString("bizContent");
                    BASE64Decoder decoder = new BASE64Decoder();
                    byte[] bytes = decoder.decodeBuffer(bizContents);
                    log.debug("bizContent解密：" + new String(bytes))
                    String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
                    log.debug("bizContent转码：" + bizContent);
                    JSONObject bizContentJson = JSONObject.fromObject(bizContent);
                    //获取客户编号
                    String callbackCustomerId = bizContentJson.getString("customerId");
                    //获取平台ID
                    String appId = bizContentJson.getString("appId");
                    //获取serialNo
                    String serialNo = bizContentJson.getString("serialNo");
                    //获取状态
                    String status = bizContentJson.getString("status");
                    //获取状态描述
                    String statusDesc = bizContentJson.getString("statusDesc");
                    //获取失败原因
                    String auditFailReason = bizContentJson.getString("auditFailReason");
                    if (KHUtil.isNull(recGuid)) {
                        result.put("code", 400);
                        result.put("msg", "recGuid必传");
                        return result.toString();
                    }
                    JSONObject authenticationCallbackResult = authenticationCallback(eliteBean, status, callbackCustomerId, batchId, auditFailReason, recGuid);
                    return authenticationCallbackResult.toString();
                case "乙方签署回调":
                    JSONObject resultJson = null;
                    //接收客户端调用参数
                    String callJson = "";
                    InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
                    BufferedReader iny = new BufferedReader(reader);
                    String line;
                    while ((line = iny.readLine()) != null) {
                        callJson += line;
                    }
                    log.info("[调用请求信息]:" + callJson);
                    JSONObject inJson = JSONObject.fromObject(callJson);
                    String bizContents = inJson.getString("bizContent");
                    BASE64Decoder decoder = new BASE64Decoder();
                    byte[] bytes = decoder.decodeBuffer(bizContents);
                    log.debug("bizContent解密：" + new String(bytes))
                    String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
                    log.debug("bizContent转码：" + bizContent);
                    JSONObject bizContentJson = JSONObject.fromObject(bizContent);
                    String docNo = bizContentJson.getString("docNo");   //获取合同编号
                    String transactionNo = bizContentJson.getString("transactionNo");   //获取接入平台交易号
                    String status = bizContentJson.getString("resultCode"); //获取状态码
                    String callbackFailReason = bizContentJson.getString("resultMsg");
                    String customerType = request.getParameter("customerType");
                    String agreementDuid = request.getParameter("agreementDuid");
                    String rejectionReason = "";
                    if (status == "2") {
                        rejectionReason = bizContentJson.getString("rejectionReason");
                    }
                    String baseCustomer = Util.filterForObject(request.getParameter("customerId"));
                    if (KHUtil.isNull(recGuid)) {
                        result.put("code", 400);
                        result.put("msg", "recGuid必传");
                        return result.toString();
                    }
                    JSONObject SignBCallResult = SignBCallback(eliteBean, status, batchId, callbackFailReason, transactionNo, recGuid, baseCustomer, rejectionReason, customerType,agreementDuid);
                    return SignBCallResult.toString();
                    break;
                case "甲方签署回调":
                    JSONObject resultJson = null;
                    //接收客户端调用参数
                    String callJson = "";
                    InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
                    BufferedReader iny = new BufferedReader(reader);
                    String line;
                    while ((line = iny.readLine()) != null) {
                        callJson += line;
                    }
                    log.info("[调用请求信息]:" + callJson);
                    JSONObject inJson = JSONObject.fromObject(callJson);
                    String bizContents = inJson.getString("bizContent");
                    BASE64Decoder decoder = new BASE64Decoder();
                    byte[] bytes = decoder.decodeBuffer(bizContents);
                    log.debug("bizContent解密：" + new String(bytes))
                    String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
                    log.debug("bizContent转码：" + bizContent);
                    JSONObject bizContentJson = JSONObject.fromObject(bizContent);
                    String docNo = bizContentJson.getString("docNo");   //获取合同编号
                    String transactionNo = bizContentJson.getString("transactionNo");   //获取接入平台交易号
                    String status = bizContentJson.getString("resultCode"); //获取状态码
                    String callbackFailReason = bizContentJson.getString("resultMsg");
                    String baseCustomer = Util.filterForObject(request.getParameter("customerId"));
                    String rejectionReason = "";
                    String signType = Util.filterForObject(request.getParameter("signType"));
                    if (status == "2") {
                        rejectionReason = bizContentJson.getString("rejectionReason");
                    }
                    if (KHUtil.isNull(recGuid)) {
                        result.put("code", 400);
                        result.put("msg", "recGuid必传");
                        return result.toString();
                    }
                    JSONObject SignACallResult = SignACallback(eliteBean, status, callbackFailReason, transactionNo, recGuid, batchId, baseCustomer, rejectionReason, signType);
                    return SignACallResult.toString();
                    break;
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取请求参数异常(" + e.getMessage() + ")");
            log.error("获取请求参数异常：" + e.getMessage());
            return result.toString();
        }
    }


    /**
     * 合同数据推送
     * @param eliteBean
     * @param batchId
     * @param CALLBACKURL
     * @param APPID
     * @param APPKEY
     * @param URL
     * @return
     */
    JSONObject pushContract(EliteBean eliteBean, String batchId) {
        JSONObject result = new JSONObject();
        JSONArray customerArray = null;
        String failCustomerId = "";
        String failRecGuid = "";
        try {
            //根据批次号获取待推送一体化客户号
            List customerList = eliteBean.chaxun_sql("select rec_guid, field_1 as CUSTOMERID,account_no  from ph_contract_sign_list where state = 1 and batch_id = '" + batchId + "' order by created_date", DATA_SOURCE);
            customerArray = JSONArray.fromObject(customerList);
            if (customerArray.size() > 0) {
                for (int j = 0; j < customerArray.size(); j++) {
                    if (flag != 0) {
                        throw new Exception("中断调用");
                    }
                    Thread.sleep(3000);
                    List fddCustomerIdList = null;
                    JSONObject customerObject = customerArray.get(j);
                    //获取法大大客户号
                    String customerId = customerObject.getString("CUSTOMERID");

                    failCustomerId = customerId;

                    String recGuid = customerObject.getString("rec_guid");

                    failRecGuid = recGuid;

                    String[] customerArr = customerId.split(",");
                    log.debug("customerArr:" + customerArr.length);

                    Integer registerCount = 0;

                    Integer authenticationCount = 0;

                    String fddCustomerId = "";
                    String FddCustomerId = "";
                    String mobile = "";
                    for (String custId : customerArr) {
                        fddCustomerIdList = eliteBean.chaxun_sql("select FDD_CUSTOMERID,mobile from customer where customerid = '" + custId + "'", DATA_SOURCE);
                        if (fddCustomerIdList.size() == 0) {
                            JSONObject register = register(eliteBean, custId);
                            if (register.has("code")) {
                                if (register.getString("code") == "200") {
                                    registerCount = registerCount + 1;
                                    fddCustomerId = register.getString("fdd_customerid");
                                    mobile = register.getString("mobile");
                                    //调用认证
                                    JSONObject authentResult = authentication(eliteBean, custId, batchId, fddCustomerId, mobile, recGuid);
                                    log.debug("调用认证返回：" + authentResult.toString());
                                    if (authentResult.getString("code") == "1") {
                                        eliteBean.update("insert into ph_callback_type values('" + recGuid + "','" + custId + "','等待认证')", DATA_SOURCE);
                                        authenticationCount = authenticationCount + 1;
                                    } else if (authentResult.getString("code") == "-1") {
                                        String failReason = authentResult.getString("msg");//获取失败原因
                                        //更新发送状态及失败原因
                                        updateFailReason(eliteBean, failReason, customerId, 3, batchId, recGuid);
                                        break;
                                    } else {
                                        Incremental = Incremental + 1;//合同编号尾数递增
                                        eliteBean.update("update ph_contract_sign_list set fdd_status = 2,state = 2,fdd_customerid ='" + fddCustomerId + "' where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                                        JSONObject createContractResult = createContract(eliteBean, batchId, recGuid);
                                        log.debug("跳过认证合同生成返回报文：" + createContractResult.toString());
                                    }
                                    FddCustomerId = FddCustomerId + fddCustomerId + ",";
                                } else {
                                    String failReason = register.getString("msg");//获取失败原因
                                    //更新发送状态及失败原因
                                    updateFailReason(eliteBean, failReason, customerId, 0, batchId, recGuid);
                                    break;
                                }
                            }
                        } else {
                            fddCustomerId = fddCustomerIdList[0].getAt("FDD_CUSTOMERID");
                            mobile = fddCustomerIdList[0].getAt("mobile");
                            log.debug("现存fddCustomerId:" + fddCustomerId);
                            //调用认证
                            JSONObject authentResult = authentication(eliteBean, custId, batchId, fddCustomerId, mobile, recGuid);
                            log.debug("调用认证返回：" + authentResult.toString());
                            if (authentResult.getString("code") == "1") {
                                authenticationCount = authenticationCount + 1;
                                eliteBean.update("insert into ph_callback_type values('" + recGuid + "','" + custId + "','等待认证')", DATA_SOURCE);
                                eliteBean.update("update ph_contract_sign_list set fdd_status = 1,state = 2 where field_1 = '" + customerId + "' and batch_id = '" + batchId + "' and rec_guid = '" + recGuid + "'", DATA_SOURCE);
                            } else if (authentResult.getString("code") == "-1") {//若已认证则跳过认证流程生成合成
                                String failReason = authentResult.getString("msg");//获取失败原因
                                //更新发送状态及失败原因
                                updateFailReason(eliteBean, failReason, customerId, 0, batchId, recGuid);
                                break;
                            } else {
                                Incremental = Incremental + 1;//合同编号尾数递增
                                eliteBean.update("update ph_contract_sign_list set fdd_status = 2,state = 2,fdd_customerid ='" + fddCustomerId + "' where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                                JSONObject createContractResult = createContract(eliteBean, batchId, recGuid);
                                log.debug("跳过认证合同生成返回报文：" + createContractResult.toString());
                            }
                            FddCustomerId = FddCustomerId + fddCustomerId + ",";
                        }
                    }
                    if (FddCustomerId != "" && FddCustomerId != null) {
                        char lastChar = FddCustomerId.charAt(FddCustomerId.length() - 1);

                        if (lastChar != ",") {
                            FddCustomerId = FddCustomerId.substring(0, FddCustomerId.length() - 1);
                        }
                    }
                    if (registerCount == customerArr.length) {
                        eliteBean.update("update ph_contract_sign_list set fdd_status = 1 where field_1 = '" + customerId + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        //更新fdd客户id
                        eliteBean.update("update ph_contract_sign_list set fdd_customerid ='" + fddCustomerId + "' where field_1 = '" + customerId + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        if (authenticationCount == customerArr.length) {
                            eliteBean.update("update ph_contract_sign_list set state = 2 where field_1 = '" + customerId + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        }
                    }
                }
            } else {
                //查询已认证但发送暂停后未生产合同的数据
                List customerList2 = eliteBean.chaxun_sql("select rec_guid, field_1 as CUSTOMERID,account_no  from ph_contract_sign_list where state = 2 and fdd_status = 2 and batch_id = '" + batchId + "' order by created_date", DATA_SOURCE);
                if (customerList2.size() > 0) {
                    JSONArray customerArray2 = JSONArray.fromObject(customerList2);
                    for (int q = 0; q < customerList2.size(); q++) {
                        JSONObject customerJson2 = customerArray2.get(q);
                        JSONObject createContractResult = createContract(eliteBean, batchId, customerJson2.getString("rec_guid"));
                    }
                }
            }
            Integer getContractListCount = eliteBean.chaxun_sql("select count(1) CON from ph_contract_sign_list where batch_id = '" + batchId + "' and state = 1 and fdd_status is not null", DATA_SOURCE)[0].getAt("CON");
            if (getContractListCount == 0) {
                eliteBean.update("update ph_contract_sign_batch set send_status = 2 where batch_id = '" + batchId + "'", DATA_SOURCE);
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "获取待推送一体化客户号异常(" + e.getMessage() + ")");
            log.error("获取待推送一体化客户号异常：" + e.getMessage());
            updateFailReason(eliteBean, "获取待推送一体化客户号异常:" + e.getMessage(), failCustomerId, 0, batchId, failRecGuid);
            return result;
        }
        result.put("code", "200");
        result.put("msg", "合同数据推送成功");
        return result;
    }


    /**
     * 注册接口
     * @param eliteBean 数据库操作工具
     * @param customerId 客户编号
     * @return
     */
    JSONObject register(EliteBean eliteBean, String customerId) {
        JSONObject result = new JSONObject();//返回报文
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("customeroid", customerId);
            map.put("key", "ca3c64a49d1f11ecbed6d703198897725e7aba55");
            def ASCIIMD5 = KHUtil.ASCIIORDER(map);
            log.debug("接口传递参数:" + ASCIIMD5);
            String customerUrl = "";
            String getCustomerResult = "";
            List getCustomerList = eliteBean.chaxun_sql("select target_url as url from sys_interface_config where type ='getCustomerinfo'", DATA_SOURCE);
            if (getCustomerList.size() == 0) {
                result.put("code", 400);
                result.put("msg", "无法获取客户详细接口的系统参数配置！");
                return result;
            } else {
                customerUrl = getCustomerList[0].getAt("url");
                log.debug("详细接口地址：" + customerUrl);
            }
            try {
                //客户详细接口调用
                getCustomerResult = Util.doHttpPost(customerUrl, ASCIIMD5.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG);
                log.debug("客户详细接口调用返回：" + getCustomerResult);
            } catch (Exception e) {
                result.put("code", 500);
                result.put("msg", "客户详细接口调用异常(" + e.getMessage() + ")");
                log.error("客户详细接口调用异常:" + e.getMessage());
                return result;
            }
            //返回数据处理
            JSONObject obj = JSONObject.fromObject(getCustomerResult);
            log.debug(obj.getString("data"));
            if (obj.getString("data") != null && obj.getString("data") != "null" && !(obj.getString("data").equals("null"))) {
                JSONObject datajson = obj.getJSONObject("data");
                String customerid = datajson.get("customerid");
                String customername = datajson.get("customername");
                String customeroid = datajson.get("customeroid");
                String customertypename = datajson.get("customertypename");
                String idno = datajson.get("idno");
                String mobile = datajson.get("mobile");
                String sex = datajson.get("sex");
                String address = datajson.get("address");
                String iscompany = datajson.get("iscompany");
                //获取法大大客户编码
                String customerGuid = "", FDDCustomerId = "";
                try {
                    List getFDDCustomerList = eliteBean.chaxun_sql("select c.customer_guid,FDD_CUSTOMERID from customer c  where c.customerid2 ='" + customeroid + "'", DATA_SOURCE);
                    if (getFDDCustomerList.size() > 0) {
                        customerGuid = getFDDCustomerList[0].getAt("customer_guid");
                        FDDCustomerId = getFDDCustomerList[0].getAt("FDD_CUSTOMERID");
                        log.debug("法大大已知客户编码:" + FDDCustomerId);
                        if (FDDCustomerId.equals("") || FDDCustomerId.equals("null")) {
                            //调用法大大注册
                            JSONObject registerResult = FDDCreateCust(eliteBean, datajson);
                            if (registerResult.getString("code") == "200") {
                                if (registerResult.has("responseData")) {
                                    FDDCustomerId = registerResult.getString("responseData");
                                    log.debug("法大大客户编码:" + FDDCustomerId);
                                }
                            }
                        }
                        eliteBean.update("update customer set customername='" + customername + "',customer_id='" + idno + "',gender='" + sex + "',mobile='" + mobile + "',idtype='" + customertypename + "',customerid2='" + customeroid + "',FDD_CUSTOMERID='" + FDDCustomerId + "',ADDRESS='" + address + "',CUSTOMERTYPE='" + iscompany + "' where customer_guid='" + customerGuid + "'", "dataSource");
                    } else {
                        customerGuid = Util.getGuid();
                        JSONObject registerResult = FDDCreateCust(eliteBean, datajson);
                        log.debug("调用注册返回：" + registerResult.toString());
                        if (registerResult.getString("code") == "200") {
                            if (registerResult.has("responseData")) {
                                FDDCustomerId = registerResult.getString("responseData");
                                log.debug("法大大客户编码:" + FDDCustomerId);
                            }
                        }
                        eliteBean.update("insert into customer(customer_guid,customername,customerid,customer_id,gender,mobile,idtype,customerid2,createdby,createddate,FDD_CUSTOMERID,ADDRESS,CUSTOMERTYPE,STRINGFIELD9) values('" + customerGuid + "','" + customername + "','" + customerid + "','" + idno + "','" + sex + "','" + mobile + "','" + customertypename + "','" + customeroid + "','SELITE',now(),'" + FDDCustomerId + "','" + address + "','" + iscompany + "','" + customerid + "')", "dataSource");
                    }
                    result.put("code", "200");
                    result.put("msg", "注册成功！");
                    result.put("cutomer_guid", customerGuid);
                    result.put("fdd_customerid", FDDCustomerId);
                    result.put("mobile", mobile);
                } catch (Exception e) {
                    result.put("code", 500);
                    result.put("msg", "客户详细数据处理异常(" + e.getMessage() + ")");
                    log.error("客户详细数据处理异常:" + e.getMessage());
                    return result;
                }
            } else {
                result.put("code", 400);
                result.put("msg", "法大大返回客户详细数据处理异常data数据为(" + obj.getString("data") + ")");
                return result;
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取客户详细接口系统参数异常(" + e.getMessage() + ")");
            log.error("获取客户详细接口系统参数异常:" + e.getMessage());
            return result;
        }
        return result;
    }

    /**法大大注册
     * @param eliteBean 数据库操作工具
     * @param datajson 注册数据报文
     * @return
     */
    private JSONObject FDDCreateCust(EliteBean eliteBean, JSONObject datajson) {
        JSONObject result = new JSONObject();
        //数据处理
        def customerid = datajson.get("customerid");
        def customername = datajson.get("customername");
        def customeroid = datajson.get("customeroid");
        def customertypename = datajson.get("customertypename");
        def idno = datajson.get("idno");
        def mobile = datajson.get("mobile");
        def sex = datajson.get("sex");
        def iscompany = datajson.get("iscompany");
        def smap;
        String url;
        try {
            smap = eliteBean.chaxun_sql("select target_url as url from sys_interface_config where type ='apiCustomerRegist'", "dataSource");
            if (smap.size() == 0) {
                result.put("code", 400);
                result.put("msg", "无法获取客户法大大注册接口的系统参数配置！");
                return result;
            } else {
                url = smap[0].getAt("url");
                log.debug("接口地址:" + url);
            };
            JSONObject jsonBody = new JSONObject();
            if (iscompany == "公司") {
                //如果是公司，先注册个人，再注册公司，传递个人为管理员
                JSONObject jsonBody0 = new JSONObject();
                jsonBody0.put("type", 1);
                jsonBody0.put("account", mobile);
                String commpanyResult = Util.doHttpPost(url, jsonBody0.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG);
                JSONObject fddobj0 = JSONObject.fromObject(commpanyResult);
                String Fdd_customid = fddobj0.get("data");
                log.debug("法大大个人认证ID返回:" + Fdd_customid)
                if (!Fdd_customid.equals("")) {
                    jsonBody.put("type", 2);
                    jsonBody.put("account", mobile);
                    jsonBody.put("companyName", customername);
                    jsonBody.put("adminAccountId", Fdd_customid)
                } else {
                    result.put("customer_guid", "");
                    result.put("customerid", "");
                    result.put("code", 400);
                    result.put("msg", "法大大企业注册失败！");
                    return result;
                }
            } else {
                jsonBody.put("type", 1);
                jsonBody.put("account", mobile);
            }
            log.debug("法大大注册参数:" + jsonBody.toString());
            String registerResult = Util.doHttpPost(url, jsonBody.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG);
            JSONObject fddobj = JSONObject.fromObject(registerResult);
            log.debug("法大大注册结果:" + fddobj);
            result.put("code", "200");
            result.put("msg", "法大大注册成功！");
            if (fddobj.getString("code") == "1" || fddobj.getString("code") == "1001003") {
                result.put("responseData", fddobj.getString("data"));
            }
            return result;
        } catch (Exception e) {
            log.error("调用注册异常信息:", e.getMessage())
            result.put("customer_guid", "");
            result.put("customerid", "");
            result.put("code", 500);
            result.put("msg", "调用注册异常信息(" + e.getMessage() + ")");
            return result;
        }
        return result;
    }

    /**认证接口
     * @param eliteBean 数据库操作工具
     * @param fddCustomerId 法大大客户编号
     * @param batchId 批次号
     * @return
     */
    JSONObject authentication(EliteBean eliteBean, String customerId, String batchId, String fddCustomerId, String mobile, String recGuid) {
        JSONObject inJson = new JSONObject();
        inJson.put("customerId", fddCustomerId);
        inJson.put("mobile", mobile);
        JSONObject result = new JSONObject();//返回报文
        try {
            //获取客户类型
            String customerTypeSql = "Select CUSTOMERTYPE From customer Where FDD_CUSTOMERID = '" + fddCustomerId + "' LIMIT 1";
            List list = eliteBean.chaxun_sql(customerTypeSql, DATA_SOURCE);
            String customerType = "";
            if (list.size() > 0) {
                customerType = list[0].getAt("CUSTOMERTYPE");
            }
            log.debug("类型：" + customerType);
            if (customerType == "个人") {
                result = personAuth(inJson, customerId, batchId, recGuid, fddCustomerId, mobile);
            } else if (customerType == "公司") {
                result = personcompanyAuth(inJson, customerId, batchId, recGuid);
            } else {
                result = personAuth(inJson, customerId, batchId, recGuid, fddCustomerId, mobile);
                /*result.put("code", -1);
                result.put("msg", "未知客户类型：" + customerType);*/
            }
            log.debug("认证返回：" + result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "调用认证异常(" + e.getMessage() + ")");
        }
        return result;
    }

    /**个人认证
     * @param inJson 接口报文
     * @param customerId 客户编号
     * @param batchId 批次号
     * @return
     */
    JSONObject personAuth(JSONObject inJson, String customerId, String batchId, String recGuid, String fddCustomerId, String mobile) {
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        inJson.put("verifiedWay", 9);
        inJson.put("pageModify", 1);
        inJson.put("isSendSms", 1);
        inJson.put("isRepeatVerified", 1);
        inJson.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=认证回调&customerId=" + customerId + "&recGuid=" + recGuid);
        log.debug("请求报文加密前：" + inJson.toString());
        String bizContent = getbizContent(inJson.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);

        log.debug("用户个人认证参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/certification/person/url", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);

        JSONObject obj = JSONObject.fromObject(Assemblys);
        log.debug("个人认证请求返回报文：" + obj.toString());
        if (obj.getString("code") == "1002021") {
            JSONObject inJsonTwo = new JSONObject();
            inJsonTwo.put("customerId", fddCustomerId);
            inJsonTwo.put("mobile", mobile);
            inJsonTwo.put("verifiedWay", 9);
            inJsonTwo.put("pageModify", 1);
            inJsonTwo.put("isSendSms", 1);
            inJsonTwo.put("isRepeatVerified", 2);
            inJsonTwo.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=认证回调&customerId=" + customerId + "&recGuid=" + recGuid);
            log.debug("参数不一致不允许继续认证,重新认证请求报文加密前：" + inJsonTwo.toString());
            String bizContents = getbizContent(inJsonTwo.toString());
            bizContents = bizContents.replaceAll("\\n", "").replaceAll("\\r", ""); ;
            JSONObject jsonsZ = new JSONObject();
            String datetimes = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsonsZ.put("timestamp", datetimes);
            jsonsZ.put("bizContent", bizContents);
            jsonsZ.put("signType", "SHA256");
            jsonsZ.put("appId", APPID);
            String signStrings = "appId=" + APPID + "&bizContent=" + bizContents + "&signType=SHA256&timestamp=" + datetimes;
            signStrings = signStrings.replace("\\n", "");

            String signstr1s = Util.getSHA256Str(signStrings).toUpperCase();
            String signstr2s = Util.getSHA256Str(signstr1s + APPKEY).toUpperCase();
            String signs = new BASE64Encoder().encodeBuffer(signstr2s.getBytes("UTF-8"));
            jsonsZ.put("sign", signs);

            log.debug("参数不一致不允许继续认证,重新认证用户个人认证参数:" + jsonsZ.toString().replace("\\n", ""));
            String AssemblysZ = Util.doHttpPostUseHead(URL + "/certification/person/url", jsonsZ.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
            obj = JSONObject.fromObject(AssemblysZ);
            log.debug("个人认证重新请求返回报文：" + obj.toString());
        }
        return obj;
    }

    /**企业认证
     * @param inJson 认证接口报文
     * @param customerId 客户编号
     * @param batchId 批次号
     * @return
     */
    JSONObject personcompanyAuth(JSONObject inJson, String customerId, String batchId, String recGuid) {
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        inJson.put("verifiedWay", 0);
        inJson.put("pageModify", 1);
        inJson.put("isSendSms", 1);
        inJson.put("isRepeatVerified", 2);//1-首次认证，2-重新认证
        inJson.put("companyPrincipalType", 2);
        inJson.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?" + batchId + "&callbackType=认证回调&customerId=" + customerId + "&callbackStatus=1&recGuid=" + recGuid);
        JSONObject AgentInfoDTO = new JSONObject();
        AgentInfoDTO.put("agentMobile", inJson.getString("mobile"));
        inJson.put("agentInfo", AgentInfoDTO);
        String bizContent = getbizContent(inJson.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);

        log.debug("用户公司认证参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/certification/company/url", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);

        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取bizContent
    String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }

    /**
     * 认证回调
     * @param eliteBean 数据库操作工具
     * @param callbackStatus 回调状态
     * @param callbackCustomerId 回调客户号
     * @param batchId 批次号
     * @param URL 法大大接口地址
     * @param APPID 法大大AAPID
     * @param APPKEY 接口签名
     * @return JSON对象
     */
    JSONObject authenticationCallback(EliteBean eliteBean, String status, String callbackCustomerId, String batchId, String auditFailReason, String recGuid) {
        JSONObject result = new JSONObject();
        try {
            if ((auditFailReason == null || auditFailReason == "") || auditFailReason == "null") {
                eliteBean.update("update ph_callback_type set type = '认证成功' where rec_guid = '" + recGuid + "' and customer_id = '" + callbackCustomerId + "'", DATA_SOURCE);
                eliteBean.update("update customer set fdd_status='" + status + "' where customerid='" + callbackCustomerId + "'", DATA_SOURCE);
                Integer typeCount = eliteBean.chaxun_sql("select count(1) CON from ph_callback_type where rec_guid = '" + recGuid + "' and type in('等待认证','认证失败')", DATA_SOURCE)[0].getAt("CON");
                if (typeCount == 0) {
                    eliteBean.update("update ph_contract_sign_list set fdd_status = 2 where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                    Incremental = Incremental + 1;//合同编号尾数递增
                    JSONObject createContract = createContract(eliteBean, batchId, recGuid);
                    log.debug("生成合同返回对象：" + createContract);
                    //生成合同
                    if (createContract.getString("code") == "1") {
                        eliteBean.update("update ph_contract_sign_list set fdd_status = 4,contract_id = '" + createContract.getString("contractId") + "' where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                    }
                }
            } else {
                updateFailReason(eliteBean, auditFailReason, callbackCustomerId, 3, batchId, recGuid);
                eliteBean.update("update customer set fdd_status='" + status + "',fdd_reason= '" + auditFailReason + "'" +
                        " where fdd_customerid='" + callbackCustomerId + "'", DATA_SOURCE);
                eliteBean.update("update ph_callback_type set type = '认证失败' where rec_guid = '" + recGuid + "' and customer_id = '" + callbackCustomerId + "'", DATA_SOURCE);
            }
            result.put("code", "200");
            result.put("msg", "合同数据认证回调成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "合同数据认证回调异常(" + e.getMessage() + ")");
            updateFailReason(eliteBean, "合同数据认证回调异常:" + e.getMessage(), callbackCustomerId, 0, batchId, recGuid);
        }
        return result;
    }

    /**生成合同
     * @param eliteBean 数据库操作工具
     * @param batchId 批次号
     * @param URL 接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @return
     */
    JSONObject createContract(EliteBean eliteBean, String batchId, String recGuid) {
        JSONObject result = new JSONObject();
        String starttime = "";
        String enddtime = "";
        String years = "";
        try {
            //获取所有法大大认证回调成功的数据
            String createContractSql = "select field_1,template_id,property_number from ph_contract_sign_list where batch_id = '" + batchId + "' and state = 2 and fdd_status = 2";
            List createContractList = eliteBean.chaxun_sql(createContractSql, DATA_SOURCE);
            JSONArray createContractArray = JSONArray.fromObject(createContractList);
            if (createContractArray.size() > 0) {
                log.debug("createContractArray大小：" + createContractArray.size());
                for (int i = 0; i < createContractArray.size(); i++) {
                    JSONObject createContract = createContractArray.get(i);
                    String customerId = createContract.getString("field_1");
                    String templateId = createContract.getString("template_id");
                    String propertyNumber = createContract.getString("property_number");
                    //根据模板id获取法大大key
                    String getFDDKeySql = "select fdd_key from fdd_contract_key where contractfileid = '" + templateId + "'";
                    //获取合同包id
                    String getFddGroupId = eliteBean.chaxun_sql("select FDDGroup_id from fdd_contract_file where contractfileid = '" + templateId + "'", DATA_SOURCE)[0].getAt("FDDGroup_id");
                    log.debug("getFddGroupId:" + getFddGroupId);
                    List getFDDKeyList = eliteBean.chaxun_sql(getFDDKeySql, DATA_SOURCE);
                    JSONArray fddKeyArray = JSONArray.fromObject(getFDDKeyList);
                    JSONObject templateJson = new JSONObject();
                    JSONObject inJson = new JSONObject();
                    //拼接合同填充信息
                    String contractDetailSql = fillTemplateContent(eliteBean, templateId, customerId, batchId);
                    log.debug("查询sql:" + contractDetailSql);
                    List contractDetailList = eliteBean.chaxun_sql(contractDetailSql, DATA_SOURCE);
                    Map<String, Object> tabcmap = contractDetailList.get(0);
                    for (String key : tabcmap.keySet()) {
                        if (key == "starttime") {
                            starttime = tabcmap.get(key).toString();
                            log.debug("starttime:" + starttime);
                        }
                        if (key == "endtime") {
                            enddtime = tabcmap.get(key).toString();
                            log.debug("enddtime:" + enddtime);
                        }
                        if (key == "years") {
                            years = tabcmap.get(key).toString();
                            log.debug("years:" + years);

                        }
                        log.debug("key:" + key);
                        templateJson.put(key, tabcmap.get(key).toString());
                    }
                    inJson.put("data", templateJson);
                    String contractId = "";
                    Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(starttime);
                    log.debug("转换后的日期：" + date);
                    String leaseTime = new SimpleDateFormat("yyyyMMdd").format(date);
                    log.debug("转换后的字符串：" + leaseTime);
                    switch (getFddGroupId) {
                        case "CLELT3":
                            //生成合同编号
                            contractId = "SZHJX-ZL-" + propertyNumber + "-" + leaseTime + KHUtil.getRandomString(4);
                            break;
                        case "H1DPF3":
                            //生成合同编号
                            contractId = "SZHJX-GD-" + propertyNumber + "-" + leaseTime + KHUtil.getRandomString(4);
                            break;
                        case "VBFWBF":
                            //生成合同编号
                            contractId = "SZHJX-TZ-" + propertyNumber + KHUtil.getRandomString(4);
                            break;
                    }
//                    contractId = recursionGetContract(eliteBean, contractId, propertyNumber);
                    log.debug("合同编号：" + contractId);

                    //获取组件列表
                    List<Object> assList = new ArrayList();
                    JSONObject assemblyPara = new JSONObject();
                    Iterator<String> keys = inJson.getJSONObject("data").keys();
                    while (keys.hasNext()) {
                        String teams = keys.next();
                        log.debug("teams: " + teams);
                        assemblyPara.put("name", teams);
                        assemblyPara.put("value", templateJson.getString(teams));
                        log.debug("assemblyPara:" + assemblyPara);
                        assList.add(assemblyPara.toString());
                        assemblyPara.clear();
                    }
                    log.debug("assList:" + assList.toString());
                    //获取合同模板控件
                    JSONObject getAssembly = getAssembly(templateId);
                    //获取甲方签名
                    List signature_pzf = eliteBean.chaxun_sql("select signature from fdd_contract_file where contractfileid = '" + templateId + "'", "dataSource");
                    String signature = signature_pzf.get(0).getAt("signature");
                    //编辑模板填充
                    JSONObject fillContract = fillContract(assList, templateId, propertyNumber, signature, contractId);
                    fillContract.put("contractId", contractId);
                    log.debug("fillContract:" + fillContract.toString());
                    if (fillContract.getString("code") != "1") {
                        String failReason = fillContract.getString("msg");
                        updateFailReason(eliteBean, failReason, customerId, 5, batchId, recGuid);
                    } else {
                        String getSignedASql = '''SELECT DISTINCT
                                                    R1.customerid as customerid,
                                                    R1.fdd_type as fdd_type,
                                                    R1.ordernum as ordernum,
                                                    CONCAT(R1.yth_gsname,'-',R1.fdd_type) as sender_name
                                                  FROM
                                                    fdd_bao_contract f
                                                  LEFT JOIN 
                                                    fdd_contract_file f2 ON f2.contractfile_guid = f.contractfile_guid
                                                  LEFT JOIN 
                                                    fdd_admin R1 ON FIND_IN_SET( R1.CUSTOMERID, F2.FDD_CUSTOMERID ) 
                                                  WHERE
                                                    f2.contractfileid = \'''' + templateId + '''\'
                                                  AND customerid!= '' ''';
                        List getSignedAList = eliteBean.chaxun_sql(getSignedASql, DATA_SOURCE);
                        JSONArray signedAArray = JSONArray.fromObject(getSignedAList);
                        //往 fdd_agreement_list 表中记录甲方数据
                        List senderGuidList = new ArrayList();
                        List senderNameList = new ArrayList();
                        if (signedAArray.size() > 0) {
                            for (int k = 0; k < signedAArray.size(); k++) {
                                JSONObject signedAObject = signedAArray.get(k);
                                String fddCustomerId = signedAObject.getString("customerid");
                                String fddType = signedAObject.getString("fdd_type");
                                String orderNum = signedAObject.getString("ordernum");
                                String senderName = signedAObject.getString("sender_name");
                                senderGuidList.add(fddCustomerId);
                                senderNameList.add(senderName);
                                String signedADealSql = '''INSERT INTO fdd_agreement_list(
                                                        agreementduid,
                                                        ModelID,
                                                        businessnumber,
                                                        contractid,
                                                        customerid,
                                                        ht_state,
                                                        ht_type,
                                                        pushsigning,
                                                        ordernum,
                                                        createddate,
                                                        createdby,
                                                        workorderid,
                                                        customertype)
                                                    values(
                                                        uuid(),
                                                        \'''' + templateId + '''\',
                                                        \'''' + propertyNumber + '''\',
                                                        \'''' + contractId + '''\',
                                                        \'''' + fddCustomerId + '''\',
                                                        '未签署',
                                                        \'''' + fddType + '''\',
                                                        '未推送',
                                                        ''' + orderNum + ''',
                                                         NOW(),
                                                        'SELITE',
                                                        '',
                                                        2
                                                    )
                                                ''';
                                int signedADealResult = eliteBean.update(signedADealSql, DATA_SOURCE);
                                log.debug("SQL返回结果：" + signedADealResult.toString());
                            }
                        } else {
                            result.put("code", 400);
                            result.put("msg", "未维护签署人！");
                            return result;
                        }
                        eliteBean.update("update ph_contract_sign_list set fdd_status = 4,contract_id = '" + contractId + "' where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        JSONObject pushPartyBSignResult = pushPartyBSign(eliteBean, batchId, senderGuidList, senderNameList, starttime, enddtime, years);
                        log.debug("推送乙方签署返回：" + pushPartyBSignResult.toString());
                        if (pushPartyBSignResult.getString("code") == "1") {
                            eliteBean.update("update ph_contract_sign_list set fdd_status = 8 where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        }
                    }
                    result = fillContract;
                    log.debug("调用合同生成返回结果:" + fillContract);

                }
            } else {
                result.put("code", 400);
                result.put("msg", "未找到待合成的数据！");
                return result;
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取法大大回调数据失败(" + e.getMessage() + ")");
            log.error("获取法大大回调数据失败:" + e.getMessage());
            return result;
        }
        return result;
    }

    /**编辑模板填充
     * @param assList 组件列表
     * @param templateId 模板id
     * @param propertyNumber 合同标题
     * @param URL 法大大接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @param companyCustomerid 企业客户编号
     * @param contractId 合同编号
     * @return
     */
    public JSONObject fillContract(List assList, String templateId, String propertyNumber, String companyCustomerid, String contractId) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        jsonPara.put("id", templateId);
        jsonPara.put("contractTitle", propertyNumber);
        jsonPara.put("contractNo", contractId);
        jsonPara.put("personCustomerId", "");
        jsonPara.put("companyCustomerId", companyCustomerid);//personCustomerId
        jsonPara.put("onlineWidgetDetailDTOS", assList);
        jsonPara.put("crossPlatform", 1);//因法大大改版新增
        String bizContent = getbizContent(jsonPara.toString());
        log.debug("编辑模板填充参数1:" + jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("编辑模板填充参数:" + jsons.toString().replace("\\n", ""));
        log.debug("合同填充请求地址：" + URL + "/online-template/fill");
        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/fill", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
        log.debug("合同生成返回结果:" + Assemblys.toString());
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    /**获取合同模板控件
     * @param Modelid 模板id
     * @param URL 法大大接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @return
     */
    public JSONObject getAssembly(String Modelid) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");

        jsonPara.put("id", Modelid);
        String bizContent = getbizContent(jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");
        log.debug("signString:" + signString);
        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        log.debug("signstr1:" + signstr1);
        log.debug("signstr1:" + signstr1 + APPKEY);
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        log.debug("signstr2:" + signstr2);
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("合同模板控件参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/widget/list", jsons.toString().replace("\\n", ""), null, TIME_OUT, ENABLE_SSL_FLAG, headMap);
        log.debug("Assemblys:" + Assemblys)
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    /** 拼接模板填充信息
     * @param eliteBean 数据库操作工具
     * @param templateId 模板id
     * @param customerId 客户编号
     * @param batchId 批次号
     * @return
     */
    String fillTemplateContent(EliteBean eliteBean, String templateId, String customerId, String batchId) {
        //获取法大大维护的模板
        List fddTemplateConfigurationList = eliteBean.chaxun_sql("select contractfileid,contractfilename from fdd_contract_file", DATA_SOURCE);
        JSONArray templateArray = JSONArray.fromObject(fddTemplateConfigurationList);
        //获取详细表字段名称
        String fieldSql = "select label_id from ph_label_sign where id > 6";
        List fieldList = eliteBean.chaxun_sql(fieldSql, DATA_SOURCE);
        JSONArray fieldArray = JSONArray.fromObject(fieldList);
        String field = "";
        for (int i = 0; i < templateArray.size(); i++) {
            JSONObject templateJson = templateArray.get(i);
            if (templateId == templateJson.getString("contractfileid")) {
                List fddKeyList = eliteBean.chaxun_sql("select fdd_key from fdd_contract_key where contractfileid = '" + templateJson.getString("contractfileid") + "'", DATA_SOURCE);
                JSONArray fddKeyJson = JSONArray.fromObject(fddKeyList);
                for (int j = 0; j < fddKeyJson.size(); j++) {
                    JSONObject fddKeyObject = fddKeyJson.get(j);
                    JSONObject fieldObject = fieldArray.get(j);
                    String fddKey = fddKeyObject.getString("fdd_key");
                    field = field + fieldObject.getString("label_id") + " as '" + fddKey + "',";
                }
                field = field.substring(0, field.length() - 1);
                break;
            }
        }
        String fddKeySql = "select " + field + " from ph_contract_sign_list where field_1 = '" + customerId + "' and batch_id = '" + batchId + "'";
        return fddKeySql;
    }

    /**
     * 推送乙方签署
     * @param eliteBean 数据库操作工具
     * @param URL 法大大接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @return
     */
    JSONObject pushPartyBSign(EliteBean eliteBean, String batchId, List senderGuidList, List senderNameList, String startTime, String endTime, String years) {
        JSONObject result = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        try {
            Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(startTime);
            Date date1 = new SimpleDateFormat("yyyy年MM月dd日").parse(endTime);
            String beginTime = new SimpleDateFormat("yyyy-MM-dd").format(date);
            String endTimes = new SimpleDateFormat("yyyy-MM-dd").format(date1);
            //获取所有合同生成成功待推送的数据
            String toBePushBSql = '''SELECT
                                        pl.rec_guid,
                                        pl.template_id as template_id,
                                        pl.field_1 as customerid,
                                        pl.fdd_customerid as fdd_customerid,
                                        pl.contract_id as contract_id,
                                        pl.property_number as property_number,
                                        pl.department_id,
                                        pl.name,
                                        fc.FDDGroup_id as FDDGroup_id
                                      FROM
                                        ph_contract_sign_list pl
                                      LEFT JOIN ph_contract_sign_batch pb ON pl.batch_id = pb.batch_id
                                      LEFT JOIN fdd_contract_file fc on pl.template_id = fc.contractfileid
                                      WHERE
                                        pl.fdd_status = 4 and pl.batch_id = \'''' + batchId + '''\' ''';
            List toBePushBList = eliteBean.chaxun_sql(toBePushBSql, DATA_SOURCE);
            JSONArray toBePushBArray = JSONArray.fromObject(toBePushBList);
            List signerGuidList = null;
            List signerNameList = null;
            if (toBePushBArray.size() > 0) {
                for (int i = 0; i < toBePushBArray.size(); i++) {
                    JSONObject jsonPara = new JSONObject();
                    JSONObject toBePushBObject = toBePushBArray.get(i);
                    String templateId = toBePushBObject.getString("template_id");
                    String customerId = toBePushBObject.getString("customerid");
                    String contractId = toBePushBObject.getString("contract_id");
                    String propertyNumber = toBePushBObject.getString("property_number");
                    String recGuid = toBePushBObject.getString("rec_guid");
                    String departmentId = toBePushBObject.getString("department_id");
                    String customerName = toBePushBObject.getString("name");
                    String fddGroup_id = toBePushBObject.getString("FDDGroup_id");
                    String[] custArr = customerId.split(",");
                    //集合不能放在外面，会带出上一个合同客户信息，每一个合同需重新在内存中创建一个对象保存
                    signerGuidList = new ArrayList();
                    signerNameList = new ArrayList();
                    signerNameList.add(customerName);
                    String customerType = "";
                    for (String custId : custArr) {
                        List getCustomerList = eliteBean.chaxun_sql("select FDD_CUSTOMERID,CUSTOMERTYPE from customer where customerid = '" + custId + "'", DATA_SOURCE);
                        String fddCustomerId = getCustomerList[0].getAt("FDD_CUSTOMERID");
                        String customerTypeName = getCustomerList[0].getAt("CUSTOMERTYPE");
                        if (customerTypeName == "公司") {
                            customerType = "2";
                        } else {
                            customerType = "1";
                        }
                        signerGuidList.add(fddCustomerId);
                        String agreementDuid = UUID.randomUUID().toString();
                        String transactionNo = Util.getMD5Str(agreementDuid);  //传参处理
                        log.debug("transactionNo:" + transactionNo);
                        log.debug("agreementDuid:" + agreementDuid);
                        eliteBean.update('''INSERT INTO fdd_agreement_list(
                                                        agreementduid,
                                                        ModelID,
                                                        businessnumber,
                                                        contractid,
                                                        customerid,
                                                        ht_state,
                                                        ht_type,
                                                        pushsigning,
                                                        ordernum,
                                                        createddate,
                                                        createdby,
                                                        workorderid,
                                                        customertype)
                                                    values(
                                                        \'''' + agreementDuid + '''\',
                                                        \'''' + templateId + '''\',
                                                        \'''' + propertyNumber + '''\',
                                                        \'''' + contractId + '''\',
                                                        \'''' + fddCustomerId + '''\',
                                                        '未签署',
                                                        '客户',
                                                        '未推送',
                                                        0,
                                                        NOW(),
                                                        'SELITE',
                                                        '',
                                                        \'''' + customerType + '''\'
                                                    )
                                                ''', DATA_SOURCE);
                        if (customerType == "2") {
                            jsonPara.put("companyCustomerId", fddCustomerId);
                            //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
                            jsonPara.put("docNo", contractId);
                            jsonPara.put("autoArchive", "2");
                            jsonPara.put("transactionNo", transactionNo);
                            jsonPara.put("notifyUrl", CALLBACKURL + "api/apiBatchSignContract?batchId=" + batchId + "&callbackType=乙方签署回调&customerType=" + customerType + "&customerId=" + customerId + "&recGuid=" + recGuid + "&agreementDuid=" + agreementDuid);


                            //第一个关键字，公司盖章
                            Map<String, String> CompanySealKeywordDTO1 = new HashMap<String, String>();
                            CompanySealKeywordDTO1.put("companyKeyWord", KHDBConfig.getParam(eliteBean, "YFQYGZ")); //关键字
                            CompanySealKeywordDTO1.put("companyKeywordStrategy", 0);
                            CompanySealKeywordDTO1.put("companyKeywordOffsetX", 30);
                            CompanySealKeywordDTO1.put("companyKeywordOffsetY", 50 * i);
                            CompanySealKeywordDTO1.put("sealName", KHDBConfig.getParam(eliteBean, "GONGZ")); //印章名称

                            //第二个关键字，法人签名
                            Map<String, String> CompanySealKeywordDTO2 = new HashMap<String, String>();
                            CompanySealKeywordDTO2.put("companyKeyWord", KHDBConfig.getParam(eliteBean, "YFQYQM")); //关键字
                            CompanySealKeywordDTO2.put("companyKeywordStrategy", 0);
                            CompanySealKeywordDTO2.put("companyKeywordOffsetX", 30);
                            CompanySealKeywordDTO2.put("companyKeywordOffsetY", 50 * i);
                            CompanySealKeywordDTO2.put("sealName", KHDBConfig.getParam(eliteBean, "FANRZ")); //印章名称

                            //将关键字拼接成list
                            List<String> companySealInfoslist = new ArrayList<>();
                            companySealInfoslist.add(CompanySealKeywordDTO1);
                            companySealInfoslist.add(CompanySealKeywordDTO2);

                            jsonPara.put("companySealInfos", companySealInfoslist);
                            if (fddGroup_id == "VBFWBF") { //如果合同模板类型是解除合同，则推送时间章关键字
                                //签署时间：传时间章关键字
                                JSONObject jsondatePara = new JSONObject();
                                jsondatePara.put("keyword", KHDBConfig.getParam(eliteBean, "YFHTQS")); //时间章关键字
                                jsondatePara.put("keywordStrategy", 0);
                                jsondatePara.put("keywordOffsetX", 30);
                                jsondatePara.put("keywordOffsetY", 50 * i);
                                jsonPara.put("dateSealKeywordDTO", jsondatePara);
                            }
                        } else {
                            jsonPara.put("customerId", fddCustomerId);
                            //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
                            jsonPara.put("docNo", contractId);
                            jsonPara.put("autoArchive", "2");
                            jsonPara.put("transactionNo", transactionNo);
                            jsonPara.put("isSendSms", 1);
                            jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=乙方签署回调&customerType=" + customerType + "&customerId=" + customerId + "&recGuid=" + recGuid + "&transactionNo=" + transactionNo + "&agreementDuid=" + agreementDuid);
                            //关键字设置
                            jsonPara.put("personKeyWord", KHDBConfig.getParam(eliteBean, "YFQMC")); //关键字
                            jsonPara.put("personKeywordStrategy", 0);
                            jsonPara.put("personKeywordOffsetX", 30);
                            jsonPara.put("personKeywordOffsetY", 50 * i);
                            if (fddGroup_id == "VBFWBF") { //如果合同模板类型是解除合同，则推送时间章关键字
                                //签署时间：传时间章关键字
                                JSONObject jsondatePara = new JSONObject();
                                jsondatePara.put("keyword", KHDBConfig.getParam(eliteBean, "YFHTQS")); //时间章关键字
                                jsondatePara.put("keywordStrategy", 0);
                                jsondatePara.put("keywordOffsetX", 30);
                                jsondatePara.put("keywordOffsetY", 50 * i);
                                jsonPara.put("dateSealKeywordDTO", jsondatePara);
                            }
                        }
                        String bizContent = getbizContent(jsonPara.toString());
                        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");
                        JSONObject jsons = new JSONObject();
                        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                        jsons.put("timestamp", datetime);
                        jsons.put("bizContent", bizContent);
                        jsons.put("signType", "SHA256");
                        jsons.put("appId", APPID);
                        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
                        signString = signString.replace("\\n", "");
                        log.debug("signString:" + signString);
                        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
                        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
                        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
                        jsons.put("sign", sign);
                        log.debug("推送乙方参数:" + jsons.toString().replace("\\n", ""));
                        String Assemblys = "";
                        if (customerType == "2") {
                            //调用法大大推送签署接口，文档编号HT103
                            Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push/customized", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
                        } else {
                            //调用法大大推送签署接口，文档编号HT103
                            Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
                        }

                        log.debug("乙方签署接口返回：" + Assemblys);

                        result = JSONObject.fromObject(Assemblys);
                        //如果code为1则标识当前客户已推送，等待签署后回调
                        if (result.getString("code") == "1") {
                            eliteBean.update("update fdd_agreement_list set pushsigning = '已推送',transactionNo = '" + transactionNo + "', pushsigningtime = now() where agreementduid = '" + agreementDuid + "'", DATA_SOURCE);
                            eliteBean.update("insert into ph_callback_type values('" + recGuid + "','" + custId + "','等待乙方签署')", DATA_SOURCE);
                            log.debug("执行了推送操作");
                        } else {
                            eliteBean.update("update fdd_agreement_list set  pushFailReason = '" + result.getString("msg") + "',transactionNo = '" + transactionNo + "' where agreementduid = '" + agreementDuid + "'", DATA_SOURCE);
                            String failReason = result.getString("msg");
                            updateFailReason(eliteBean, failReason, customerId, 6, batchId, recGuid);
                        }
                    }
                    log.debug("signerNameList集合大小：" + signerNameList.size());
                    log.debug("signerGuidList集合大小：" + signerGuidList.size());
                    eliteBean.update("insert into fdd_contract_list( contractlist_guid, contractid, contracttype, contractfileid, businessnumber, departmentoid, signer_guid, signer_name, sender_guid, sender_name, leaseapplicationtimestart, leaseapplicationtimesend, currentapplicationperiod, createddate) " +
                            "values( UUID(), '" + contractId + "', '2', '" + templateId + "',  '" + propertyNumber + "', '" + departmentId + "', '" + signerGuidList + "', '" + signerNameList.join('/') + "', '" + senderGuidList + "', '" + senderNameList.join('/') + "', '" + beginTime + "', '" + endTimes + "', '" + years + "', NOW())", DATA_SOURCE);
                }
            } else {
                result.put("code", "400");
                result.put("msg", "未找到合同生成成功待推送数据");
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "获取合同生成成功待推送数据异常(" + e.getMessage() + ")");
            log.error("获取合同生成成功待推送数据异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 乙方签署回调
     * @param eliteBean 数据库操作工具
     * @param callbackStatus 回调状态
     * @param callbackCustomerId 回调客户id
     * @param batchId 回调批次号
     * @param URL 法大大接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @return
     */
    JSONObject SignBCallback(EliteBean eliteBean, String status, String batchId, String callbackFailReason, String transactionNo, String recGuid, String baseCustomer, String rejectionReason, String customerType,String agreementDuid) {
        JSONObject result = new JSONObject();
        try {
            if (status == "1" || status == "10040019") {
                //根据批次号和客户编号获取等待乙方签署的合同数据
                String getContractSql = "select contract_id,fdd_customerid from ph_contract_sign_list where batch_id = '" + batchId + "' and rec_guid = '" + recGuid + "' and fdd_status = 8";
                List getContractList = eliteBean.chaxun_sql(getContractSql, DATA_SOURCE);
                if (getContractList.size() > 0) {
                    //获取合同编号
                    String contractId = getContractList[0].getAt("contract_id");
                    //获取法大大客户id
                    String fddCustomerId = getContractList[0].getAt("fdd_customerid");
                    //根据合同编号及法大大客户id获取已推送合同的agreementduid
                    /*String getAgreementDuid = eliteBean.chaxun_sql("select agreementduid from fdd_agreement_list  where contractid = '" + contractId + "' and pushsigning = '已推送' and customertype =" + customerType + " and customerid = '" + fddCustomerId + "'", DATA_SOURCE)[0].getAt("agreementduid");*/
                    eliteBean.update("update fdd_agreement_list set ht_state='已签署',ht_statetime=now() where agreementduid='" + agreementDuid + "'", DATA_SOURCE);
                    eliteBean.update("update ph_callback_type set type = '乙方签署成功' where rec_guid = '" + recGuid + "' and customer_id = '" + baseCustomer + "'", DATA_SOURCE);
                    eliteBean.update("update customer set fdd_status='" + status + "',fdd_reason= '" + callbackFailReason + "'" +
                            " where fdd_customerid='" + baseCustomer + "'", DATA_SOURCE);
                    //检查是否存在客户未签署
                    Integer CON = eliteBean.chaxun_sql("select count(1) CON from fdd_agreement_list where contractid='" + contractId + "' and ht_state='未签署' and ht_type='客户'", "dataSource")[0].getAt("CON");
                    //推送甲方签署
                    if (CON == 0) {
                        JSONObject pushPartyASignResult = pushPartyASign(eliteBean, batchId, baseCustomer, recGuid, "公司", contractId);
                        if (pushPartyASignResult.getString("code") == "1") {
                            //将合同批次详情的法大大状态更新为等待公司签署(甲方)
                            eliteBean.update("update ph_contract_sign_list set fdd_status = 9 where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                            result.put("code", "200");
                            result.put("msg", "乙方签署回调成功！");
                        }
                    }
                }
            } else if (status == "2") { //已拒签
                eliteBean.update("update fdd_agreement_list set ht_state = '已拒签', rejectionReason='" + rejectionReason + "', resultCode = '" + status + "', resultMsg = '" + callbackFailReason + "', resultTime = now() where transactionNo='" + transactionNo + "'", DATA_SOURCE);
                updateFailReason(eliteBean, callbackFailReason, baseCustomer, 12, batchId, recGuid);
                result.put("code", "400");
                result.put("msg", "乙方已拒签！");
            } else {
                updateFailReason(eliteBean, callbackFailReason, baseCustomer, 12, batchId, recGuid);
                eliteBean.update("update fdd_agreement_list set rejectionReason='" + callbackFailReason + "' where transactionNo='" + transactionNo + "'", DATA_SOURCE);
                result.put("code", "400");
                result.put("msg", "乙方签署回调失败！");
            }
        } catch (Exception e) {
            updateFailReason(eliteBean, "乙方签署回调失败：" + e.getMessage(), baseCustomer, 0, batchId, recGuid);
        }
        return result;
    }

    /**
     * 推送甲方签署
     * @param eliteBean 数据库操作工具
     * @param batchId 批次id
     */
    JSONObject pushPartyASign(EliteBean eliteBean, String batchId, String callbackCustomerId, String recGuid, String htType, String contractId) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        String autoArchive = "";
        //结果标识
        JSONObject pushresults = new JSONObject();
        try {
            //根据合同号查询所有待甲方公司签署的合同
            String waitSignPartyASql = '''SELECT
                                            fl.agreementduid,
                                            fl.customerid,
                                            fl.customertype,
                                            fl.ht_type,
                                            fl.ordernum,
                                            fl.contractid
                                          FROM
                                            fdd_agreement_list fl
                                          left join ph_contract_sign_list pl on fl.contractid = pl.contract_id
                                          WHERE
                                            pl.batch_id = \'''' + batchId + '''\' 
                                            AND fl.customertype = 2 
                                            AND fl.pushsigning = '未推送'
                                            AND ht_type = \'''' + htType + '''\'
                                            AND contractid = \'''' + contractId + '''\' ''';
            List waitSignPartyAList = eliteBean.chaxun_sql(waitSignPartyASql, DATA_SOURCE);
            JSONArray waitSignPartyAArray = JSONArray.fromObject(waitSignPartyAList);
            //查询所推送甲方最大的数字
            String maxOrderNum = eliteBean.chaxun_sql("select max(ordernum) as ordernum from fdd_agreement_list where contractid = (select contract_id from ph_contract_sign_list where batch_id = '" + batchId + "' and field_1 = '" + callbackCustomerId + "' and rec_guid = '" + recGuid + "')", DATA_SOURCE)[0].getAt("ordernum");
            //遍历所有待甲方签署的合同
            for (int i = 0; i < waitSignPartyAArray.size(); i++) {
                JSONObject waitSignPartyAObject = waitSignPartyAArray.get(i);
                String agreementDuid = waitSignPartyAObject.getString("agreementduid");
                String customerId = waitSignPartyAObject.getString("customerid");
                String customerType = waitSignPartyAObject.getString("customertype");
                String minOrderNum = waitSignPartyAObject.getString("ordernum");
                //判断是否自动归档
                if (maxOrderNum == minOrderNum) {
                    autoArchive = "1";
                } else {
                    autoArchive = "2";
                }
                //查询推送甲方类型对应法大大个人编号、企业编号、签字位置、时间位置
                List fddList = eliteBean.chaxun_sql("select customerid, companyCustomerid, seal_location, date_location from fdd_admin where customerid = '" + customerId + "' and fdd_type = '" + htType + "' order by ordernum asc", DATA_SOURCE);
                //企业签署时：个人客户编号不传，则默认推送给企业管理员代表企业签署；个人客户编号有传，则该个人代表企业签署
                String fddCustomerId = fddList[0].getAt("customerid");
                String companyCustomerId = fddList[0].getAt("companyCustomerid");
                //甲方盖章处
                String sealLocation = fddList[0].getAt("seal_location");
                //甲方签章日期
                String dateLocation = fddList[0].getAt("date_location");

                //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
                String transactionNo = Util.getMD5Str(agreementDuid);
                jsonPara.put("customerId", fddCustomerId);
                jsonPara.put("companyCustomerId", companyCustomerId);
                jsonPara.put("docNo", contractId);
                jsonPara.put("autoArchive", autoArchive);
                jsonPara.put("transactionNo", transactionNo);
                jsonPara.put("isSendSms", 1);
                jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=甲方签署回调&customerId=" + callbackCustomerId + "&signType=" + htType + "&recGuid=" + recGuid);
                jsonPara.put("companyKeyWord", sealLocation);
                jsonPara.put("companyKeywordStrategy", 0);

                JSONObject jsondatePara = new JSONObject();
                jsondatePara.put("keyword", dateLocation);
                jsondatePara.put("keywordStrategy", 0);
                jsonPara.put("dateSealKeywordDTO", jsondatePara);

                String bizContent = getbizContent(jsonPara.toString());
                bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
                JSONObject jsons = new JSONObject();
                String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                jsons.put("timestamp", datetime);
                jsons.put("bizContent", bizContent);
                jsons.put("signType", "SHA256");
                jsons.put("appId", APPID);
                String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
                signString = signString.replace("\\n", "");

                String signstr1 = Util.getSHA256Str(signString).toUpperCase();
                String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
                String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
                jsons.put("sign", sign);
                log.debug("推送门户签署参数:" + jsons.toString().replace("\\n", ""));
                String Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
                log.debug("推送门户签署返回:" + Assemblys.toString());
                JSONObject obj = JSONObject.fromObject(Assemblys);
                String type = "";
                if (htType == "公司") {
                    type = "等待公司签署(甲方)";
                } else if (htType == "法人") {
                    type = "等待法人签署(甲方)";
                }
                //如果code为1则标识当前客户已推送，等待签署后回调
                if (obj.getString("code") == '1') {
                    eliteBean.update("update fdd_agreement_list set pushsigning = '已推送', pushsigningtime = now(), " +
                            "transactionNo = '" + transactionNo + "' where agreementduid = '" + agreementDuid + "'", "dataSource");
                    eliteBean.update("update ph_callback_type set type = '" + type + "' where rec_guid = '" + recGuid + "' and customer_id = '" + callbackCustomerId + "'", DATA_SOURCE);
                } else {
                    pushresults.put("code", "400");
                    pushresults.put("msg", "存在未成功推送");
                    String failReason = pushresults.getString("msg");
                    updateFailReason(eliteBean, failReason, customerId, 7, batchId, recGuid);
                }
                pushresults = obj;
            }
        } catch (Exception e) {
            pushresults.put("code", "500");
            pushresults.put("msg", "推送甲方签署异常（" + e.getMessage() + ")");
            log.error("推送甲方签署异常：" + e.getMessage());
        }
        return pushresults;
    }

    /**
     * 甲方签署回调
     * @param eliteBean 数据库操作工具
     * @param callbackStatus 回调状态
     * @param callbackCustomerId 回调客户号
     * @param batchId 批次id
     * @param URL 法大大接口地址
     * @param APPID 法大大APPID
     * @param APPKEY 接口签名
     * @return
     */
    JSONObject SignACallback(EliteBean eliteBean, String status, String callbackFailReason, String transactionNo, String recGuid, String batchId, String baseCustomer, String rejectionReason, String signType) {
        JSONObject result = new JSONObject();
        try {
            if (status == "1") {
                String getContractSql = "";
                if (signType == "公司") {
                    getContractSql = "select contract_id,fdd_customerid from ph_contract_sign_list where batch_id = '" + batchId + "' and field_1 = '" + baseCustomer + "' and fdd_status = 9";
                } else if (signType == "法人") {
                    getContractSql = "select contract_id,fdd_customerid from ph_contract_sign_list where batch_id = '" + batchId + "' and field_1 = '" + baseCustomer + "' and fdd_status = 10";
                }
                List getContractList = eliteBean.chaxun_sql(getContractSql, DATA_SOURCE);
                if (getContractList.size() > 0) {
                    //获取合同编号
                    String contractId = getContractList[0].getAt("contract_id");
                    eliteBean.update("update fdd_agreement_list set ht_state='已签署',ht_statetime=now() where transactionNo='" + transactionNo + "'", DATA_SOURCE);
                    if (signType == "公司") {
                        JSONObject pushAResult = pushPartyASign(eliteBean, batchId, baseCustomer, recGuid, "法人", contractId);
                        if (pushAResult.getString("code") == "1") {
                            //将合同批次详情的法大大状态更新为等待法人签署(甲方)
                            eliteBean.update("update ph_contract_sign_list set fdd_status = 10 where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        }
                    }
                    //检查是否存在客户未签署
                    Integer CON = eliteBean.chaxun_sql("select count(1) CON from fdd_agreement_list where contractid='" + contractId + "' and ht_state='未签署' and ht_type <> '客户'", "dataSource")[0].getAt("CON");
                    //推送甲方签署
                    if (CON == 0) {
                        //将合同批次详情的法大大状态更新为签署完成
                        eliteBean.update("update ph_contract_sign_list set fdd_status = 13 where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'", DATA_SOURCE);
                        eliteBean.update("update fdd_contract_list set signingresults='1' where contractid='" + contractId + "'", "dataSource");
                        result.put("code", "200");
                        result.put("msg", "甲方签署回调成功！");
                    }
                }
            } else if (status == "2") { //已拒签
                eliteBean.update("update fdd_agreement_list set ht_state = '已拒签', rejectionReason='" + rejectionReason + "', resultCode = '" + status + "', resultMsg = '" + callbackFailReason + "', resultTime = now() where transactionNo='" + transactionNo + "'", "dataSource");
            } else {
                updateFailReason(eliteBean, callbackFailReason, baseCustomer, 12, batchId, recGuid);
                eliteBean.update("update fdd_agreement_list set rejectionReason='" + callbackFailReason + "' where transactionNo='" + transactionNo + "'", "dataSource");
                result.put("code", "400");
                result.put("code", "甲方签署回调失败！");
            }
        } catch (Exception e) {
            updateFailReason(eliteBean, "甲方签署回调失败：" + e.getMessage(), baseCustomer, 0, batchId, recGuid);
        }
        return result;
    }

    /**
     * 更新状态
     * @param eliteBean 数据库操作工具
     * @param failReason 失败原因
     * @param customerId 一体化客户号
     * @param fddStatus 法大大状态
     */
    void updateFailReason(EliteBean eliteBean, String failReason, String customerId, Integer fddStatus, String batchId, String recGuid) {
        StringBuffer updSql = new StringBuffer("update ph_contract_sign_list set failed_resean = '" + failReason + "' ");
        if (fddStatus != 0) {
            updSql.append(",fdd_status = " + fddStatus + "");
        }
        if (fddStatus != 12 && fddStatus != 5) {
            updSql.append(" ,state = -1 ")
        }
        updSql.append(" where rec_guid = '" + recGuid + "' and batch_id = '" + batchId + "'");
        eliteBean.update(updSql.toString(), DATA_SOURCE);
    }

    /**
     * 递归获取不重复的合同编号
     * @param eliteBean
     * @param contractId
     * @param propertyNumber
     * @return
     */
/*    String recursionGetContract(EliteBean eliteBean, String contractId, String propertyNumber) {
        int loopLimit = 0;
        //判断合同编号是否已生成
        Integer getContractIdCount = eliteBean.chaxun_sql("select count(1) CON from ph_contract_sign_list where contract_id ='" + contractId + "'", DATA_SOURCE)[0].getAt("CON");
        if (getContractIdCount > 0 && loopLimit < 1000)  {
            String beforeChar = contractId.substring(0,contractId.length() - 1);
            String afterChar = contractId.substring(contractId.length() - 1,contractId.length());
            Integer num = Integer.parseInt(afterChar) + 1;
            contractId = beforeChar + afterChar + num.toString();
            loopLimit ++;
            return recursionGetContract(eliteBean, contractId, propertyNumber);
        } else {
            return contractId;
        }
    }*/

}